package demo.algorithm;

import org.apache.commons.math3.stat.StatUtils;

import java.util.Arrays;

public class Demo {


    public static void main(String[] args) {
        double[] data = {10.2, 8.5, 12.1, 9.7, 11.3, 100.0}; // 增加一个离群值 100.0

        double[] outliers = findOutliersByZScore(data, 2.0); // 阈值设置为 2.0
        System.out.println("离群值为: " + Arrays.toString(outliers));
    }

    public static double[] findOutliersByZScore(double[] data, double threshold) {
        double mean = Arrays.stream(data).average().orElse(0.0);
        double variance = StatUtils.variance(data);  // 方差，也即：double variance = Arrays.stream(data).map(x -> Math.pow(x - mean, 2)).average().orElse(0.0);
        double stdDeviation = Math.sqrt(variance);

        double[] outliers = Arrays.stream(data)
                .filter(value -> Math.abs((value - mean) / stdDeviation) > threshold)  // 差值，并除以数据的标准差
                .toArray();

        return outliers;
    }
}
